<template>
  <div class="container">
    <el-form :inline="true" label-position="right" class="search-form">
      <el-form-item label="人员名称" v-if="status === 'meber'">
        <el-input
          class="filter-item"
          v-model="name"
          placeholder="请输入"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" v-if="status === 'meber'"
          >查询</el-button
        >
        <el-button @click="reset" v-if="status === 'meber'">重置</el-button>
      </el-form-item>
    </el-form>
    <PropTable
      :columns="processedColumn"
      :data="list"
      :total="total"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      class="dailt-table"
    >
      <template #otherSearch>
        <el-form-item label="名字" style="margin: 0px 0px 0px 0px">
          <el-cascader
            v-model="addressList"
            ref="ref_areaCodes"
            :options="areaCodelist"
            :props="areaCodeprops"
            clearable
          ></el-cascader>
        </el-form-item>
      </template>

      <template v-slot:submited="scope">
        <el-tag :type="typeColor(scope.row.submited)">
          {{
            useEmpty(scope.row.submited)
              ? ""
              : scope.row.submited === "1"
              ? "已提交"
              : "未提交"
          }}
        </el-tag>
      </template>

      <template v-slot:createTime="scope">
        <div v-if="!useEmpty(scope.row.createTime)">
          {{ formatDate(scope.row.createTime) }}
        </div>
      </template>

      <template v-slot:operation="scope">
        <el-button
          type="primary"
          link
          v-if="scope.row.submited === '0'"
          icon="Edit"
          @click="approvalAdd(scope.row)"
        >
          {{ buttonTitle }}
        </el-button>

        <el-button
          type="primary"
          link
          v-if="scope.row.submited === '1'"
          icon="Message"
          @click="approvalDetails(scope.row)"
        >
          查看
        </el-button>
        <el-button
          link
          type="danger"
          icon="Delete"
          @click="handelDelect(scope.row)"
        >
          删除</el-button
        >

        <el-button
          v-if="scope.row.checkState === '0'"
          type="primary"
          icon="Edit"
          link
          @click="handelEdit(scope.row)"
        >
          编辑
        </el-button>
      </template>
      <!-- 项目成员日报 -->
      <template #btn>
        <div style="display: flex; justify-content: space-between">
          <el-button
            :type="button1Color ? 'success' : 'primary'"
            @click="myReport(0)"
          >
            {{ buttonText }}
          </el-button>
          <el-button
            :type="button2Color ? 'success' : 'primary'"
            @click="meberReport(1)"
          >
            {{ meberText }}
          </el-button>
        </div>
      </template>
    </PropTable>
  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  computed,
  watch,
  watchEffect,
  onBeforeUnmount,
  onBeforeUpdate,
  onUpdated,
  onUnmounted,
} from "vue";
//@ts-ignore
import PropTable from "@/components/Table/PropTable/index.vue";

//@ts-ignore
import {
  dailyList,
  memberList,
  deleReport,
  memberSearch,
} from "@/api/information/daily";
//@ts-ignore
import { useEmpty, formatDate } from "@/utils/index";

import { useRouter, useRoute } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus";
import useUserStore from "@/store/modules/user";

const router = useRouter();
const userStore = useUserStore();
const route = useRoute();
const props = defineProps({
  activeIndex: {
    type: Number,
    required: true,
  },
});

const buttonTitle = ref("");
const name = ref("");

const buttonText = ref("我的日报");
const meberText = ref("成员日报");

// 标签颜色
const typeColor = (val) => {
  if (val && val === "1") {
    return "primary";
  } else {
    return "warning";
  }
};

// const loading = ref(true);
const column = ref([
  {
    name: "username",
    label: "成员",
    // inSearch: true,
    // valueType: "input",
  },
  {
    name: "taskDate",
    label: "简报周期",
  },

  {
    name: "createTime",
    label: "提交时间",
    slot: true,
  },
  { name: "submited", label: "状态", slot: true },
  { name: "operation", slot: true, fixed: "right", width: 300, label: "操作" },
]);

const status = ref("");

let hideUsernameColumn = ref(false); // 根据实际情况设置为 true 或 false

// 控制username的显示与隐藏
let processedColumn = computed(() => {
  // 检查当前页面或其他条件，决定是否隐藏 username 字段
  if (hideUsernameColumn.value) {
    //如果需要隐藏 username 字段，则从 column 数组中过滤掉该字段
    return column.value.filter((col) => col.name !== "username");
  }
  return column.value;
});

let activeName = ref();
let type = 0;

const title = () => {
  if (activeName.value === "0") {
    return (buttonTitle.value = "写日报");
  } else if (activeName.value === "1") {
    return (buttonTitle.value = "写周报");
  } else {
    return (buttonTitle.value = "写月报");
  }
};

const list = ref([]);

let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

// 我的日报列表
const dailyDataList = async () => {
  hideUsernameColumn.value = true;
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };
  if (activeName.value === "0") {
    type = 1;
  } else if (activeName.value === "1") {
    type = 2;
  } else {
    type = 3;
  }
  params["type"] = type;
  const res = await dailyList(params);
  // console.log(res.rows.length)
  if (res.code === 200 && res.rows.length >= 0) {
    list.value = res.rows;
    total.value = Number(res.total);
  } else {
    ElMessage.error(res.msg);
    // loading.value = false;
  }
};

// 成员日报列表
const dailyMemberList = async () => {
  hideUsernameColumn.value = false;
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };

  if (activeName.value === "0") {
    type = 1;
  } else if (activeName.value === "1") {
    type = 2;
  } else {
    type = 3;
  }
  params["type"] = type;
  params["name"] = name.value;
  const response = await memberList(params);
  if (response.code === 200 && response.rows.length >= 0) {
    list.value = response.rows;
    total.value = Number(response.total);
  } else {
    ElMessage.error(response.msg);
    // loading.value = false;
  }
};

let typeId = 0;
const handelSearch = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
  };

  if (activeName.value === "0") {
    typeId = 1;
  } else if (activeName.value === "1") {
    typeId = 2;
  } else {
    typeId = 3;
  }
  params["typeId"] = typeId;
  params["name"] = name.value;
  const response = await memberSearch(params);
  if (response.code === 200 && response.rows.length >= 0) {
    list.value = response.rows;
    total.value = Number(response.total);
  } else {
    ElMessage.error(response.msg);
    // loading.value = false;
  }
};

const onSubmit = async () => {
  await handelSearch();
};

const reset = async () => {
  pageNum.value = 1;
  pageSize.value = 10;
  name.value = "";
  await handelSearch();
};

// 监听 activeIndex 的变化
watchEffect(async () => {
  activeName.value = props.activeIndex;
  // status.value = "my"

  // route.query.statu = "my";
  //  dailyDataList()
});

// 写日报
const approvalAdd = (value) => {
  router.push({
    path: "/myProject/information-info/add",
    query: {
      time: value.taskDate,
      state: "未提交",
      id: value.id,
      type: value.type,
    },
  });
};

// 查看
const approvalDetails = (value) => {
  router.push({
    path: "/myProject/information-info/details",
    query: {
      time: value.taskDate,
      statu: status.value,
      state: "已提交",
      id: value.id,
      type: value.type,
      name: "3",
    },
  });
};

// 编辑
const handelEdit = (row) => {
  router.push({
    path: "/myProject/information-info/add",
    query: {
      edit: 2,
      time: row.taskDate,
      statu: status.value,
      state: "已提交",
      id: row.id,
      type: row.type,
    },
  });
};

// 删除

const handelDelect = (row) => {
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      if (row && row.id) {
        const result = await deleReport(row.id);
        if (result.code === 200) {
          // 删除成功的提示
          ElMessage.success(result.msg);
          await dailyDataList();
        }
      }
    })
    .catch((err) => {
      // 用户点击取消执行的操作
      // ElMessage.error(result.msg);
      console.log(err);
    });
};

const button1Color = ref(false);

const myButton = () => {
  if (activeName.value === "0") {
    return (buttonText.value = "我的日报");
  } else if (activeName.value === "1") {
    return (buttonText.value = "我的周报");
  } else {
    return (buttonText.value = "我的月报");
  }
};

const meberButton = () => {
  if (activeName.value === "0") {
    return (meberText.value = "成员日报");
  } else if (activeName.value === "1") {
    return (meberText.value = "成员周报");
  } else {
    return (meberText.value = "成员月报");
  }
};

// 我的日报
const myReport = async (buttonNumber) => {
  status.value = "my";
  router.replace({
    query: {
      statu: "my",
    },
  });
  await dailyDataList();
  await myButton();

  hideUsernameColumn.value = true;
  button1Color.value = false;
  button2Color.value = false;

  if (buttonNumber === 0) {
    // 设置颜色状态
    button1Color.value = true;
  }
  //  emit("myReport",  status.value);
};

const button2Color = ref(false);

// 点击查看成员日报
const meberReport = async (buttonNumber) => {
  status.value = "meber";
  router.replace({
    query: {
      statu: "meber",
    },
  });
  await meberButton();
  await dailyMemberList();

  button1Color.value = false;
  button2Color.value = false;
  if (buttonNumber === 1) {
    // 设置颜色状态
    button2Color.value = true;
  }
  //  emit("meberReport",  status.value);
};

// const emit = defineEmits([
//   "myReport",
//   "meberReport",
// ]);

const handleSizeChange = async (valueSise) => {
  pageSize.value = valueSise;
  if (status.value === "my") {
    await dailyDataList();
  } else {
    if (name.value) {
      await handelSearch();
    } else {
      await dailyMemberList();
    }
  }
};

const handleCurrentChange = async (valuePage) => {
  pageNum.value = valuePage;
  if (status.value === "my") {
    await dailyDataList();
  } else {
    if (name.value) {
      await handelSearch();
    } else {
      await dailyMemberList();
    }
  }
};

onMounted(async () => {
  button1Color.value = true;
  await title();
  await meberButton();
  // if (route.query.statu && route.query.statu === "my") {
  //   await myReport(0);
  // } else {
  //   await meberReport(1);
  // }
  setTimeout(async () => {
    if (route.query.statu === "meber") {
      await meberReport(1);
    } else {
      if (!route.query.statu) {
        router.replace({
          query: {
            statu: "my",
          },
        });
      }
      await myReport(0);
    }
  }, 100);
});

defineExpose({
  //暴露想要传递的值或方法
  status,
  myReport,
});

// onUnmounted(() => {
//   sessionStorage.removeItem("activeTab");
//   sessionStorage.removeItem("activeIndex");
// });
//  onBeforeUnmount(()=>{
//     {
//     sessionStorage.removeItem('activeTab'); // 清除 localStorage 中保存的标签页状态
//     sessionStorage.removeItem("activeIndex");
//   }
//  })
</script>
<style scoped lang="scss">
.container {
  padding: 0px 20px;
}
.dailt-table {
  max-height: 85vh;
  height: 75vh;
}
</style>
